import React, { useState, useCallback } from 'react';
import clsx from 'clsx';
import styles from './styles.module.css';

interface PhoneticSoundProps {
  text: string;
  type?: 1 | 2;  // 1: 英音, 2: 美音
  size?: 'small' | 'medium' | 'large';
  className?: string;
}

const VolumeIcon = () => (
  <svg 
    viewBox="0 0 24 24" 
    fill="currentColor"
    xmlns="http://www.w3.org/2000/svg"
  >
    <path d="M3 9v6h4l5 5V4L7 9H3zm13.5 3c0-1.77-1.02-3.29-2.5-4.03v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"/>
  </svg>
);

export const PhoneticSound: React.FC<PhoneticSoundProps> = ({
  text,
  type = 1,
  size = 'medium',
  className,
}) => {
  const [isPlaying, setIsPlaying] = useState(false);
  const [audio, setAudio] = useState<HTMLAudioElement | null>(null);

  // 防抖处理
  const playSound = useCallback(() => {
    if (isPlaying) {
      return;
    }

    // 如果已经有音频实例，先销毁
    if (audio) {
      audio.pause();
      audio.remove();
    }

    // 创建新的音频实例
    const newAudio = new Audio(`https://dict.youdao.com/dictvoice?type=${type}&audio=${encodeURIComponent(text)}`);
    setAudio(newAudio);

    // 播放处理
    setIsPlaying(true);
    newAudio.play().catch((error) => {
      console.error('播放失败:', error);
      setIsPlaying(false);
    });

    // 播放结束处理
    newAudio.onended = () => {
      setIsPlaying(false);
      newAudio.remove();
      setAudio(null);
    };
  }, [text, type, audio, isPlaying]);

  return (
    <button
      type="button"
      onClick={playSound}
      disabled={isPlaying}
      className={clsx(
        styles.soundButton,
        styles[size],
        { [styles.playing]: isPlaying },
        className
      )}
      title={`播放${type === 1 ? '英音' : '美音'}`}
    >
      <VolumeIcon />
    </button>
  );
};

export default PhoneticSound; 